const mysql = require('mysql2/promise');
const winston = require('../utils/logger');
const path = require('path');

// 确保在正确的位置加载环境变量
const envPath = path.join(__dirname, '../../.env');
require('dotenv').config({ path: envPath });
winston.info('环境变量文件路径:', { envPath });

class Database {
    constructor() {
        if (Database.instance) {
            return Database.instance;
        }
        this.pool = null;
        Database.instance = this;
    }

    async init() {
        try {
            // 检查环境变量是否存在
            const requiredEnvVars = ['DB_HOST', 'DB_USER', 'DB_PASSWORD', 'DB_NAME', 'DB_PORT'];
            const missingEnvVars = requiredEnvVars.filter(varName => !process.env[varName]);
            
            if (missingEnvVars.length > 0) {
                throw new Error(`Missing required environment variables: ${missingEnvVars.join(', ')}`);
            }

            // 打印环境变量（不包含敏感信息）
            winston.info('数据库环境变量:', {
                DB_HOST: process.env.DB_HOST,
                DB_USER: process.env.DB_USER,
                DB_NAME: process.env.DB_NAME,
                DB_PORT: process.env.DB_PORT,
                hasPassword: process.env.DB_PASSWORD ? 'yes' : 'no'
            });

            this.pool = await mysql.createPool({
                host: process.env.DB_HOST,
                user: process.env.DB_USER,
                password: process.env.DB_PASSWORD,
                database: process.env.DB_NAME,
                port: process.env.DB_PORT,
                waitForConnections: true,
                connectionLimit: 10,
                queueLimit: 0
            });

            // 测试连接
            const connection = await this.pool.getConnection();
            winston.info('数据库连接成功', {
                database: process.env.DB_NAME,
                threadId: connection.threadId
            });
            connection.release();
            return this;

        } catch (error) {
            winston.error('数据库连接失败:', error);
            throw error;
        }
    }

    async execute(sql, params) {
        if (!this.pool) {
            await this.init();
        }
        try {
            const [results] = await this.pool.execute(sql, params);
            return results;
        } catch (error) {
            winston.error('SQL执行错误:', error);
            throw error;
        }
    }

    getPool() {
        return this.pool;
    }
}

// 创建单例实例
const db = new Database();

// 导出实例
module.exports = db; 